package com.txtdhis.consumer.util;


import com.txtdhis.common.domain.User;
import com.txtdhis.common.util.Constant;
import com.txtdhis.consumer.exception.CustomException;
import com.txtdhis.consumer.manage.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * 获取当前登录用户工具类
 *
 * @author
 * @date 2021/3/15 11:45
 */
@Component
@Slf4j
@PropertySource("classpath:config.properties")
public class UserUtil {


    /**
     * RefreshToken过期时间
     */
    @Value("${shiroCacheExpireTime}")
    private String shiroCacheExpireTime;

    private UserService userservice;

    @Autowired
    public void setUserService (UserService userservice) {
        this.userservice = userservice;
    }

    /**
     * 获取当前登录用户
     *
     * @param
     * @return com.txtdhis.common.domain.User
     * @author
     * @date 2021/3/15 11:48
     */
    public User getUser() {

        String token = SecurityUtils.getSubject().getPrincipal().toString();
        User user = new User();
        // 解密获得username
        String username = JwtUtil.getClaim(token, Constant.ACCOUNT);
        log.info("username--------------------------"+username);
        //先查缓存，如果没有再查数据库并放到缓存
        if(JedisUtil.exists(Constant.user_supplier+username)){
            user = (User)JedisUtil.getObject(Constant.user_supplier+username);
        }else {
            user.setUsername(username);
            user = userservice.queryUserForList(user).get(0);
            JedisUtil.setObject(Constant.user_supplier+username,user,Integer.parseInt(shiroCacheExpireTime));
        }


        // 用户是否存在
        if (user == null) {
            throw new CustomException("该帐号不存在(The account does not exist.)");
        }
        return user;
    }

    /**
     * 获取当前登录用户Id
     *
     * @param
     * @return  com.txtdhis.common.domain.User
     * @author
     * @date 2021/3/15 11:48
     */
    public Integer getUserId() {
        return getUser().getId();
    }

    /**
     * 获取当前登录用户Token
     *
     * @param
     * @return  com.txtdhis.common.domain.User
     * @author
     * @date 2021/3/15 11:48
     */
    public String getToken() {
        return SecurityUtils.getSubject().getPrincipal().toString();
    }

    /**
     * 获取当前登录用户Account
     *
     * @param
     * @return  com.txtdhis.common.domain.User
     * @author
     * @date 2021/3/15 11:48
     */
    public String getUsername() {
        String token = SecurityUtils.getSubject().getPrincipal().toString();
        // 解密获得Account
        return JwtUtil.getClaim(token, Constant.ACCOUNT);
    }
}
